package com.muc.plugin.handler;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Element;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.handler.IQHandler;
import org.jivesoftware.util.TaskEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;

import com.muc.plugin.task.MUCJoinBoardCastTask;
import com.muc.plugin.vo.MemberJoinVO;
import org.xmpp.packet.PacketError;

/**
 * <iq type="set" id="685-6">
 * <query xmlns="xls:muc-join">
 * <roomJid>zhangsan@conference.gbei.com</roomJid>
 * <jid>admin@gbei.com</jid>
 * <nick>昵称</nick>
 * </query>
 * </iq>
 * 添加成员到 房间
 * 暂时不用,使用openfire自带的
 * 只是发送通知,最终还是由用户主动加入的
 */
public class MUCJoinIQHandler extends IQHandler {

    private IQHandlerInfo info;

    private static final String MODULE_NAME = "join room";

    private static final String NAME_SPACE = "xls:muc-join";

    private static final Logger log = LoggerFactory.getLogger(MUCJoinIQHandler.class);

    public MUCJoinIQHandler() {
        super(MODULE_NAME);
        info = new IQHandlerInfo("query", NAME_SPACE);
    }

    @Override
    public IQHandlerInfo getInfo() {
        return info;
    }

    @Override
    public IQ handleIQ(IQ packet) throws UnauthorizedException {
        //创建需要返回IQ包
        IQ reply = IQ.createResultIQ(packet);
        reply.setID(packet.getID());
        reply.setChildElement("muc", NAME_SPACE);

        List<MemberJoinVO> joins = new ArrayList<MemberJoinVO>();
        Element iq = packet.getElement();
        Element query = iq.element("query");
        MemberJoinVO vo = new MemberJoinVO();
        vo.setJid(query.elementTextTrim("jid").toLowerCase());
        vo.setNickname(query.elementTextTrim("nick").toLowerCase());
        if (null != vo.getJid() || null != vo.getNickname()) {
            reply.setError(PacketError.Condition.item_not_found);
            return reply;
        }
        joins.add(vo);
        String roomJidStr = query.elementText("roomJid");
        JID roomJid = null;
        if (roomJidStr != null) {
            roomJid = new JID(roomJidStr);
        } else {
            reply.setType(IQ.Type.error);
            log.warn("error result: " + reply.toXML());
            return reply;
        }

        TaskEngine.getInstance().schedule(new MUCJoinBoardCastTask(roomJid, joins, packet.getFrom()), 1000);
        reply.setChildElement("roomJid", roomJid.toBareJID());
        reply.setType(IQ.Type.result);
        log.info("success result: " + reply.toXML());
        return reply;
    }

}
